package cheeese.and.crackers;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import android.content.Context;

/**
 * Class representing the applications list of users.
 * @author Cheese and Crackers
 *
 */
public class UserList {
	
	static String USER_LIST_FILE_NAME = "user_list_storage";
	
	private ArrayList<User> users;
	
	/**
	 * Default constructor to initialize array list.
	 */
	public UserList(){
		users = new ArrayList<User>();
	}
	
	/**
	 * Adds a user to the list.
	 * 
	 * @param newUser The User to be added
	 */
	public void addUser(User newUser) throws Exception{
			if(getUser(newUser.getLoginId()) == null){
				if(newUser.getName().equals("")){
					throw new Exception("Invalid Name");
				}
				if(newUser.getEmail().equals("")){
					throw new Exception("Invalid Email");
				}
				if(newUser.getLoginId().equals("")){
					throw new Exception("Invalid Login Id");
				}
				if(newUser.getPassword().equals("")){
					throw new Exception("Invalid Password");
				}
				users.add(newUser);
			}
			else{
				throw new Exception("Login Id Already Exists");
			}
	}
	
	/**
	 * Returns a user with the given login ID	
	 * @param loginId The login ID of the user to get
	 * @return The user requested
	 */
	public User getUser(String loginId){
		for(int i = 0; i<users.size(); i++){
			if(users.get(i).getLoginId().equals(loginId)){
				return users.get(i);
			}
		}
		return null;
	}
	
	/**
	 * Saves userlist to system
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * 
	 * @param The context of the application
	 */
	public void save(Context context) throws FileNotFoundException, IOException{
   		ObjectOutputStream userFileOut = new ObjectOutputStream(context.openFileOutput(USER_LIST_FILE_NAME, Context.MODE_PRIVATE));
   		userFileOut.writeObject(users);
		userFileOut.close();
	}
		
	
	/**
	 * Loads userlist from system
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @throws StreamCorruptedException 
	 * @throws ClassNotFoundException 
	 * 
	 * @param context The context of the application
	 */
	public void load(Context context) throws StreamCorruptedException, FileNotFoundException, IOException, ClassNotFoundException{
		ObjectInputStream userFileIn = new ObjectInputStream(context.openFileInput(USER_LIST_FILE_NAME));
		users = (ArrayList<User>) (userFileIn.readObject());
		userFileIn.close();
	}
}
